#include "imutex.h"

IMutex::IMutex()
{
	initialized = false;
}

IMutex::~IMutex()
{
	if (initialized)
#ifdef WIN32
		CloseHandle(mutex);
#else
		pthread_mutex_destroy(&mutex);
#endif
}

int IMutex::Init()
{
	if (initialized)
		return ERR_IMUTEX_ALREADYINIT;

#ifdef WIN32
	mutex = CreateMutex(NULL,FALSE,NULL);
	if (mutex == NULL)
		return ERR_IMUTEX_CANTCREATEMUTEX;
#else
	pthread_mutex_init(&mutex, NULL);
#endif
	initialized = true;
	return 0;
}

int IMutex::Lock()
{
	if (!initialized)
		return ERR_IMUTEX_NOTINIT;

#ifdef WIN32
	WaitForSingleObject(mutex,INFINITE);
#else
	pthread_mutex_lock(&mutex);
#endif
	return 0;
}

int IMutex::Unlock()
{
	if (!initialized)
		return ERR_IMUTEX_NOTINIT;

#ifdef WIN32
	ReleaseMutex(mutex);
#else
	pthead_mutex_unlock(&mutex);
#endif
	return 0;
}

